package io.renren.service.impl;

import io.renren.dao.MsgReceiveDao;
import io.renren.dao.VEmpInfoDao;
import io.renren.entity.MsgReceiveEntity;
import io.renren.entity.VEmpInfoEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.renren.dao.EmpMsgSendDao;
import io.renren.entity.EmpMsgSendEntity;
import io.renren.service.EmpMsgSendService;
import org.springframework.transaction.annotation.Transactional;


@Service("empMsgSendService")
public class EmpMsgSendServiceImpl implements EmpMsgSendService {
	@Autowired
	private EmpMsgSendDao empMsgSendDao;

	@Autowired
	private MsgReceiveDao msgReceiveDao;

	@Autowired
	private VEmpInfoDao vEmpInfoDao;

	@Override
	public EmpMsgSendEntity queryObject(Integer id){
		return empMsgSendDao.queryObject(id);
	}
	
	@Override
	public List<EmpMsgSendEntity> queryList(Map<String, Object> map){
		return empMsgSendDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return empMsgSendDao.queryTotal(map);
	}
	
	@Override
	@Transactional
	public void save(EmpMsgSendEntity empMsgSend){
		String[] receivers = empMsgSend.getReceivers();

		List<MsgReceiveEntity> empMsgSendEntities = new ArrayList();
		if (receivers != null && receivers.length > 0) {
			StringBuffer recs = new StringBuffer("");
			//把接受人id存到信息接收表
			for (String rec : receivers) {
				recs.append(rec);
				recs.append(",");
			}
			//接收人存到数据库，以逗号隔开
			recs.deleteCharAt(recs.length() - 1);
			empMsgSend.setReceiver(recs.toString());
		}
			empMsgSendDao.save(empMsgSend);

		for (String rec:receivers) {
			MsgReceiveEntity msg = new MsgReceiveEntity();
			msg.setMsgSendId(empMsgSend.getId());
			msg.setReceiver(Integer.valueOf(rec));
			msg.setIfRead(0);
			empMsgSendEntities.add(msg);
		}

		msgReceiveDao.saveBatch(empMsgSendEntities);
	}

	@Override
	public void update(EmpMsgSendEntity empMsgSend){
		empMsgSendDao.update(empMsgSend);
	}
	
	@Override
	public void delete(Integer id){
		empMsgSendDao.delete(id);
	}
	
	@Override
	public void deleteBatch(Integer[] ids){
		empMsgSendDao.deleteBatch(ids);
	}

	@Override
	public Map<String, Object> getListinfo() {
		Map<String, Object> map = new HashMap<>();
		Map<String, Object> param = new HashMap<>();
		param.put("iswork","1");
		List<VEmpInfoEntity> emps = vEmpInfoDao.queryList(param);
		map.put("emps",emps);

		return map;
	}
}
